import React, { useEffect, useState, useRef, useCallback } from 'react'
import {
  Space,
  Table,
  Tag,
  Input,
  Button,
  Select,
  Popconfirm,
  Modal,
  Flex,
  theme,
  Tooltip,
  message
} from 'antd'
import { marked } from 'marked'
import type { TableProps } from 'antd'
import { PlusOutlined } from '@ant-design/icons'

import request from '@/api/request.ts'
import { current } from '@reduxjs/toolkit'

import { SimpleMdeReact } from 'react-simplemde-editor'
import 'easymde/dist/easymde.min.css'


interface DataType {
  key: string
  name: string
  age: number
  address: string
  tags: string[]
}

const headers = {
  Authorization:'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imp5a2wiLCJ1c2VySWQiOjQ3NTI5NTU1LCJyb2xlIjoxLCJpYXQiOjE3MzU1NDg3ODksImV4cCI6MTczODE0MDc4OX0.QgKf6srco9KYjIPGmf_7MH-TtgF5FUP9_ssYudDqR8k',
}
const pageData1 = {
  total: 0, //总页数
  current: 1, //页码 TODO 接口需要：page
  pageSize: 6, //每页显示条数
}
//搜索数据
const seartData1 = {
  keyword:'',//搜索标题
    tag:'',//搜索标签
}

const tagInputStyle: React.CSSProperties = {
  width: 64,
  height: 22,
  marginInlineEnd: 8,
  verticalAlign: 'top',
}
const Article: React.FC = () => {
  // 查看弹框
  const [isModalOpen, setIsModalOpen] = useState(false)
  // 新增弹框
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
  
  //表格数据
  const [tableData, setTableData] = useState([])
  // 页码数据对象
  const [pageData, setPageData] = useState(pageData1)
  // 搜索数据对象
  const [seartData, setSeartData] = useState(seartData1)
  // 标签otp数据对象
  const [tagOptList, setTagOptList] = useState([])
  // 文章内容
  const [articleConten, setArticleConten] = useState('')

  //新增加文件相关
  const [tags, setTags] = useState<string[]>(['Node', 'HTTP', 'React'])
  const [inputVisible, setInputVisible] = useState(false)
  const [inputValue, setInputValue] = useState('')

  const inputRef = useRef<InputRef>(null)

  const columns: TableProps<DataType>['columns'] = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '标签',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => {
        // console.log('tags', tags)
        return (
          <>
            {tags.map((tag) => {
              let color = tag.length > 5 ? 'geekblue' : 'green'
              if (tag === 'loser') {
                color = 'volcano'
              }
              return (
                <Tag color={color} key={tag.name}>
                  {tag.name}
                </Tag>
              )
            })}
          </>
        )
      },
    },
    {
      title: '分类',
      dataIndex: 'categories',
      key: 'categories',
      render: (_, { categories }) => (
        <>
          {categories?.map((tag) => {
            return <Tag key={tag.name}>{tag.name}</Tag>
          })}
        </>
      ),
    },
    {
      title: '浏览数',
      dataIndex: 'viewCount',
      key: 'viewCount',
    },
    {
      title: '发布时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              setIsModalOpen(true)
              const htmlStr = marked(record.content)
              setArticleConten(htmlStr)
            }}
          >
            查看
          </a>
          <a>编辑</a>
          <a>导出</a>
          <Popconfirm
            title="删除"
            description="确认删除吗？"
            onConfirm={(e) => {
              confirmDel(record.id)
              console.log('record', record)
            }}
            //   onCancel={cancel}
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  //表格列表接口
  const getTableData = (argms) => {
    const { current: page, pageSize } = pageData

    const params = argms || {
      page,
      pageSize,
    }
    request({
      url: 'article/list',
      method: 'get',
      params,
    }).then((res) => {
      //   console.log('res', res.rows)
      const { rows, count } = res || {}
      setTableData(rows)

      setPageData({ ...pageData, total: count })
    })
  }

  const getTagQuery = () => {
    request({ url: 'tag/list', method: 'get' }).then((res) => {
      console.log('res', res)
      setTagOptList(
        res.map((item) => {
          const { name } = item
          return { label: name, value: name }
        })
      )
    })
  }
  useEffect(() => {
    // const backPg = JSON.parse(JSON.stringify(pageData))
    // backPg.page = backPg.current
    // delete backPg.current
    // delete backPg.total

    getTableData()
    getTagQuery()
  }, [pageData.current]) //JSON.stringify(pageData)

  // 切页
  const onPageChange = (current, pageSize) => {
    // console.log('page, pageSize', current, pageSize)
    setPageData({ ...pageData, current, pageSize })
  }
  // 输入标题搜索
  const titleChange = (e) => {
    // console.log('e', e.target.value)
    setSeartData({ ...seartData, keyword: e.target.value })
  }

  //点击搜索按钮
  const onSearch = () => {
    const { current: page, pageSize } = pageData
    const { keyword, tag } = seartData
    let param = {
      page,
      pageSize,
      keyword,
    }
    if (tag) param = { ...param, tag }
    getTableData(param)
  }
  // 下拉select选择标签
  const handleChange = (value: string) => {
    console.log(`selected ${value}`)
    setSeartData({ ...seartData, tag: value })
  }
  // 删除
  const confirmDel = (delId) => {
    request({
      url: `article/${delId}`,
      method: 'DELETE',
      headers,
    }).then((res) => {
      console.log('res', res)
      getTableData()
    })
  }
  // 打开查看弹框
  const handleOk = () => {
    setIsModalOpen(false)
     setIsCreateModalOpen(false)
  }
  // 关闭查看
  const handleCancel = () => {
    setIsModalOpen(false)
    setIsCreateModalOpen(false)
  }
  // 新增tag相关

  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus()
    }
  }, [inputVisible])

  const handleClose = (removedTag: string) => {
    const newTags = tags.filter((tag) => tag !== removedTag)
    console.log(newTags)
    setTags(newTags)
  }

  const showInput = () => {
    setInputVisible(true)
  }

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value)
  }

  const handleInputConfirm = () => {
    if (inputValue && !tags.includes(inputValue)) {
      setTags([...tags, inputValue])
    }
    setInputVisible(false)
    setInputValue('')
  }


  const tagPlusStyle: React.CSSProperties = {
    height: 22,
    background: '#f3f3f3',
    borderStyle: 'dashed',
  }


  //选种标签的值
  const [selectedTags, setSelectedTags] = React.useState<string[]>([])
  const handleTagChange = (tag: string, checked: boolean) => {

    const nextSelectedTags = checked
      ? [...selectedTags, tag]
      : selectedTags.filter((t) => t !== tag)
    // console.log('You are interested in: ', nextSelectedTags)
    setSelectedTags(nextSelectedTags)
  }

// markdown编辑器

 const markTitleRef = useRef(null)
// markdown的文本
 const [markValue, setMarkValue] = useState('我是测试的')
 const onMarkChange = useCallback((value: string) => {
    console.log('value', markTitleRef.current.input.value)
   setMarkValue(value)
 }, [])
  
 //新增加
 const addArticle = ()=>{
    if(!markTitleRef.current.input.value){
        alert('请输入标题')
    }
    if (!markValue)
        alert('请输入内容')
      const data = {
        title: markTitleRef.current.input.value,
        content: markValue,
        tagList: selectedTags,
        authorId: 47529555,
      }
    request({
      url: 'article',
      method: 'post',
      headers,
      data,
    }).then((res) => {
        console.log('res', res)
        message.success('新增加文章成功')
         setIsCreateModalOpen(false)
    })
 }

  return (
    <>
      <Input
        style={{ width: '200px' }}
        placeholder="输入关键字"
        onChange={titleChange}
      />

      <Select
        defaultValue=""
        allowClear={true}
        style={{ width: 120 }}
        onChange={handleChange}
        options={tagOptList}
      />
      <Button onClick={onSearch}>检索</Button>
      <Button onClick={() => setIsCreateModalOpen(true)}>新增</Button>
      <Table<DataType>
        columns={columns}
        dataSource={tableData}
        pagination={{
          position: ['bottom'],
          ...pageData,
          onChange: onPageChange,
        }}
      />

      <Modal
        title="查看文章"
        width={900}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <div dangerouslySetInnerHTML={{ __html: articleConten }}></div>
      </Modal>

      <Modal
        title="新建文章"
        width={900}
        open={isCreateModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <div>
          <p>
            标题：<Input placeholder="请输入标题" ref={markTitleRef}></Input>
          </p>
          <p>
            标签：
            {
              <Flex gap="4px 0" wrap>
                {tags.map<React.ReactNode>((tag, index) => {
                  const isLongTag = tag.length > 20
                  const tagElem = (
                    <Tag.CheckableTag
                      key={tag}
                      closable={index !== 0}
                      style={{ userSelect: 'none' }}
                      onClose={() => handleClose(tag)}
                      checked={selectedTags.includes(tag)}
                      onChange={(checked) => handleTagChange(tag, checked)}
                    >
                      <span>{tag}</span>
                    </Tag.CheckableTag>
                  )
                  return isLongTag ? (
                    <Tooltip title={tag} key={tag}>
                      {tagElem}
                    </Tooltip>
                  ) : (
                    tagElem
                  )
                })}
                {inputVisible ? (
                  <Input
                    ref={inputRef}
                    type="text"
                    size="small"
                    style={tagInputStyle}
                    value={inputValue}
                    onChange={handleInputChange}
                    onBlur={handleInputConfirm}
                    onPressEnter={handleInputConfirm}
                  />
                ) : (
                  <Tag
                    style={tagPlusStyle}
                    icon={<PlusOutlined />}
                    onClick={showInput}
                  >
                    New Tag
                  </Tag>
                )}
              </Flex>
            }
          </p>
          <p>
            <SimpleMdeReact value={markValue} onChange={onMarkChange} />
          </p>
          <Button type="primary" onClick={addArticle}>
            确定
          </Button>
        </div>
      </Modal>
    </>
  )
}

export default Article
